package com.rpdrg.config;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

/**
 * @author 邢东阳
 * @mail hnxdyl@163.com
 * 读取客户端的配置文件
 * */
@SuppressWarnings({"unchecked", "rawtypes"})
public class InitConfig {
	public static Map configMap = new HashMap();
	
	public static void main(String[] args){
		new InitConfig().getInitConfig("F:\\Config.xml");
	}
	/**
	 * 读取客户端的Config.xml文件
	 * xml文件的格式如下：
	 * */
	public Map getInitConfig(String fileName){
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		}
		Document doc = null;
		try {
			try {
				doc = db.parse(new File(fileName));
			} catch (SAXException e) {
				e.printStackTrace();
			}
		} catch (DOMException dom) {
			dom.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		Element elRoot = doc.getDocumentElement();
		Element ele = null;
		//System.out.println(this.getAttrValue(elRoot, "Version"));
		ele = (Element) elRoot.getElementsByTagName("ServerInfo").item(0);
		String server = this.getAttrValue(ele, "UrlServer");
		String serverPort = this.getAttrValue(ele, "UrlPort");
		
		configMap.put("Version", this.getAttrValue(elRoot, "Version"));
		configMap.put("UrlServer", server);
		configMap.put("UrlPort", serverPort);
		
		List<FileVersion> fileLst = new ArrayList<FileVersion>();
		NodeList nodelst = elRoot.getElementsByTagName("File"); 
		//System.out.println(nodelst.getLength()+"**********");
		for(int i =0 ;i<nodelst.getLength();i++){
			FileVersion fileVer = new FileVersion();
			fileVer.setName( this.getAttrValue((Element)nodelst.item(i), "Name"));
			fileVer.setPath(this.getAttrValue((Element)nodelst.item(i), "Path"));
			fileVer.setSunVer(this.getAttrValue((Element)nodelst.item(i), "SubVer"));
			fileLst.add(fileVer);
		}
		configMap.put("fieInfo", fileLst);
		return configMap;
	}
	
	/**
	 * 获取XMl元素
	 * @param ele
	 * @param name
	 * @return
	 */
	private String getAttrValue(Element ele, String name)
	{
		NodeList nlName = ele.getElementsByTagName(name);
		Element elName = (Element) nlName.item(0);
		Text text = (Text) elName.getFirstChild();
		String strValue = "";
		if (text != null) {
			strValue = text.getNodeValue();
		}
		return strValue;
	}
}
